<?php

/**
 * DynamicPhoneNumberForm
 * 
 * Form class that can dynamically display multiple embedded phone number forms
 * 
 * @author Maximilian Lenkeit <dev@lenki.com>
 */
class DynamicPhoneNumberForm extends BaseForm {
  
  /**
   * Phone number owning entity
   * @var MultiPhoneNumberPossessorInterface
   */
  protected $entity;
  
  public function __construct(MultiPhoneNumberPossessorInterface $entity) {
    $this->entity = $entity;
    parent::__construct ();
  }
  
  public function configure() {
    foreach ( $this->entity->getPhoneNumbers () as $phone_number ) {
      $this->addForm ( $phone_number );
    }
    $this->addForm ();
    $this->mergePostValidator ( new EmbeddedPhoneNumberValidatorSchema () );
  }
  
  /**
   * Add embedded phone number form
   * @param PhoneNumber $phone_number
   * @param integer $num
   */
  public function addForm(PhoneNumber $phone_number = null, $num = null) {
    if (is_null ( $num )) {
      $num = $this->getNumEmbeddedForms ();
    }
    $form = new EmbeddedPhoneNumberForm ( $phone_number );
    $this->embedForm ( $num, $form );
  }
  
  /**
   * Get number of embedded forms
   * @return integer
   */
  public function getNumEmbeddedForms() {
    return count ( $this->embeddedForms );
  }
  
  /**
   * Get phone numbers of embedded forms
   * @return Doctrine_Collection
   */
  public function getPhoneNumbers() {
    $phone_numbers = new Doctrine_Collection('PhoneNumber');
    foreach($this->embeddedForms as $form) {
      if($form instanceof EmbeddedPhoneNumberForm) {
        $phone_number = $form->getObject();
        // TODO Is there a check necessary for not adding empty objects?
        $phone_numbers->add($phone_number);
      }
    }
    return $phone_numbers;
  }
}